<template>
  <!-- 新增广告 -->
  <div class="app-container">
    <!-- 广告信息 -->
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>广告信息</span>
      </div>
      <div class="text item">
        <el-form
          ref="infoForm"
          :model="infoForm"
          :rules="infoRules"
          label-width="80px"
          label-position="left"
        >
          <el-form-item label="广告商" prop="userId">
            <el-input v-model="infoForm.userId"></el-input>
          </el-form-item>

          <el-form-item label="广告名称" prop="name">
            <el-input v-model="infoForm.name"></el-input>
          </el-form-item>

          <el-row>
            <el-col :span="12">
              <el-form-item label="广告类型" prop="type">
                <!-- <el-input v-model="infoForm.type"></el-input> -->
                <el-select v-model="infoForm.type" placeholder="请选择类型">
                  <el-option
                    v-for="item in typeDataList"
                    :key="item.idStr"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="投放位置" prop="position">
                <!-- <el-input v-model="infoForm.position"></el-input> -->
                <el-select v-model="infoForm.position" placeholder="请选择类型">
                  <el-option
                    v-for="item in positionDataList"
                    :key="item.idStr"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="广告标签">
            <!-- <el-input v-model="infoForm.label"></el-input> -->
            <el-select
              v-model="labelListData"
              multiple
              placeholder="请选择标签"
            >
              <el-option
                v-for="item in labelDataList"
                :key="item.idStr"
                :label="item.content"
                :value="item.idStr"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="投放区域">
            <!-- <el-input v-model="infoForm.scope"></el-input> -->
            <el-row>
              <el-col :span="8">
                <el-select
                  v-model="province"
                  filterable
                  placeholder="请选择省份"
                  @change="areaData"
                >
                  <el-option
                    v-for="item in provincesList"
                    :key="item.code"
                    :label="item.name"
                    :value="[item.id, item.code]"
                  >
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="12">
                <el-select
                  v-model="city"
                  :disabled="cityDisabled"
                  filterable
                  placeholder="请选择市区"
                  @change="areaData"
                >
                  <el-option
                    v-for="item in citysList"
                    :key="item.code"
                    :label="item.name"
                    :value="[item.id, item.code]"
                  >
                  </el-option>
                </el-select>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item label="广告封面">
            <!-- <el-input v-model="infoForm.url"></el-input> -->
            <!-- <el-upload class="upload-demo"
                       drag
                       :on-change="changeImgInfo"
                       action="#"
                       list-type="picture-card"
                       :auto-upload="false">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip"
                   slot="tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload> -->

            <el-upload
              ref="pictureUpload"
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              accept="image/jpeg,image/gif,image/png,image/bmp"
              :limit="1"
              :on-exceed="handleExceed"
              :on-change="changeImgInfo"
            >
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{ file }">
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                  :alt="file.name"
                />

                <span class="el-upload-list__item-actions">
                  <!-- <span class="el-upload-list__item-preview"
                        @click="handlePictureCardPreview(file)">
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handleDownload(file)">
                    <i class="el-icon-download"></i>
                  </span> -->
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemoveImg(file)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
          </el-form-item>

          <el-form-item label="链接地址" prop="url">
            <el-input v-model="infoForm.url"></el-input>
          </el-form-item>

          <el-row>
            <el-col :span="12">
              <el-form-item label="开始时间" prop="start">
                <!-- <el-input v-model="infoForm.start"></el-input> -->
                <el-date-picker
                  v-model="infoForm.start"
                  type="datetime"
                  :picker-options="startPickerOptions"
                  placeholder="选择日期时间"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间" prop="end">
                <!-- <el-input v-model="infoForm.end"></el-input> -->
                <el-date-picker
                  v-model="infoForm.end"
                  type="datetime"
                  :picker-options="endPickerOptions"
                  placeholder="选择日期时间"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="状态" prop="status">
            <!-- <el-input v-model="infoForm.status"></el-input> -->
            <el-radio v-model="infoForm.status" label="0">正常</el-radio>
            <el-radio v-model="infoForm.status" label="1">停用</el-radio>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 价格设置 -->
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>价格设置</span>
      </div>
      <div class="text item">
        <el-form
          ref="priceForm"
          :model="priceForm"
          :rules="priceRules"
          label-width="150px"
          label-position="left"
        >
          <el-form-item label="每次点击价格(元)" prop="price">
            <el-input-number
              v-model="priceForm.price"
              size="medium"
              :precision="2"
              :step="0.1"
              label="描述文字"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="预算金额(元)" prop="budget">
            <!-- <el-input type="number" v-model="priceForm.budget"></el-input> -->
            <el-input-number
              v-model="priceForm.budget"
              size="medium"
              :precision="2"
              :step="0.1"
              label="描述文字"
            ></el-input-number>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 按钮 -->
    <el-row>
      <el-col :span="12" class="col-button">
        <el-button type="info" plain @click="resetForm('infoForm', 'priceForm')"
          >重置</el-button
        >
        <el-button type="primary" @click="submitForm('infoForm', 'priceForm')"
          >保存</el-button
        >
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { provincesList, cityList } from "@/wss/utils/area/index.js";
import {
  getAdListApi,
  getAdAddApi,
} from "@/wss/api/systemManagement/advert/advert.js";

import { getAddDataApi, getListDataApi, getEditDataApi } from "@/wss/api/label";
import { getBase64, convertBase64ToBlob } from "@/wss/utils/handleImage.js";

export default {
  data() {
    return {
      disabled: false,

      // 开始时间
      startPickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      // 结束时间
      endPickerOptions: {},

      /**
       * 省份 市区
       * provincesList,
       * citysList,
       */
      provincesList: undefined,
      citysList: undefined,
      province: undefined,
      city: undefined,
      cityDisabled: true, // 市区 是否显示
      labelListData: undefined, // 标签数据

      // 广告信息表单
      infoForm: {
        userId: undefined, // 用户来的
        name: undefined,
        type: undefined,
        labelList: [],
        url: undefined,
        scope: undefined,
        position: undefined,
        start: undefined,
        end: undefined,
        status: "0",
        base64: undefined, //img base64
        filename: undefined, //img file 名字
      },
      infoRules: {
        name: [{ required: true, message: "请输入广告名称", trigger: "blur" }],
        type: [
          { required: true, message: "请选择逛该类型", trigger: "change" },
        ],
        url: [{ required: true, message: "请选择链接地址", trigger: "blur" }],
        province: [
          { required: true, message: "请选择投放区域", trigger: "change" },
        ],
        position: [
          { required: true, message: "请选择投放位置", trigger: "change" },
        ],
        start: [
          { required: true, message: "请选择开始时间", trigger: "change" },
        ],
        end: [{ required: true, message: "请选择结束时间", trigger: "change" }],
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
      },

      priceForm: {
        price: undefined,
        budget: undefined, //预算金额
      },
      priceRules: {
        price: [{ required: true, message: "请输入点击价格", trigger: "blur" }],
        budget: [
          { required: true, message: "请选择预算金额", trigger: "blur" },
        ],
      },

      /**
       * 广告标签
       */
      labelDataList: [],
      /**
       * 广告类型
       */
      typeDataList: [
        {
          label: "图文广告",
          value: 1,
        },
        {
          label: "视频广告",
          value: 2,
        },
      ],
      /**
       * 投放位置
       */
      positionDataList: [
        {
          label: "放心里",
          value: 1,
        },
        {
          label: "投个🔨",
          value: 2,
        },
      ],
    };
  },
  mounted() {
    this.provincesList = provincesList;
    if (this.$route.query.id) {
      this.getAdListApiMet({ id: this.$route.query.id });
    }
    this.getListDataApiMet();
  },
  methods: {
    areaData(data) {
      console.log("aaa:", data);
      // provincesList: undefined,
      // citysList: undefined,
      // province: undefined,
      // city: undefined,
      let ID = data[0];
      let CODE = data[1];

      if (this.city == undefined) {
        this.citysList = cityList.filter((item, index, array) => {
          if (index != 0 && ID == item.pid) {
            return true;
          }
        });
        this.cityDisabled = false;
      } else {
        this.infoForm.scope = CODE;
      }

      console.log("info:", this.infoForm);
    },
    // 获取列表--标签 api
    async getListDataApiMet(pagination = null) {
      let result = await getListDataApi(pagination).then((res) => res);
      if (result.code == 200) {
        console.log(result.rows, "标签管理返回数据");
        // this.tableList = result.rows;
        this.labelDataList = result.rows;
        // this.pagination.total = result.total;
      }
    },
    // 广告列表
    async getAdListApiMet(data) {
      console.log(data);
      let result = await getAdListApi(data);
      console.log("广告列表：", result);
      this.infoForm = result.rows[0];

      // 结束时间 不能在开始时间之前
      this.endPickerOptions.disabledDate = (time) => {
        return time.getTime() < new Date(this.infoForm.start).getTime();
      };
    },
    // 添加接口 --广告信息
    async getAdAddApiMet(data) {
      let result = await getAdAddApi(data);
      console.log(result);
      if (result.code == 200) {
        this.resetForm("infoForm", "priceForm");
      }
    },

    // 图片上传----------------- S

    // 上传img 勾子
    changeImgInfo(files, fileList) {
      console.log(files, "系统管理");
      console.log(typeof fileList);

      getBase64(files.raw).then((res) => {
        this.infoForm.base64 = res.split(",")[1];

        // let blodImage = convertBase64ToBlob(res)
        // console.log("res:", URL.createObjectURL(blodImage))
      });

      this.infoForm.filename = files.name;
    },
    // 限制上传个数
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 长图片`);
    },

    // 删除勾子
    handleRemoveImg(files) {
      console.log(files);
      this.$refs.pictureUpload.uploadFiles = [];
    },

    // 图片上传----------------- E

    // 确定按钮操作
    submitForm(infoForm, priceForm) {
      this.$refs[infoForm].validate((valid) => {
        if (valid) {
          this.$refs[priceForm].validate((p) => {
            if (p) {
              // 转成时间戳
              let START = new Date(this.infoForm.start).getTime();
              let END = new Date(this.infoForm.end).getTime();
              this.infoForm.start = START;
              this.infoForm.end = END;
              this.labelListData.forEach((item) => {
                this.infoForm.labelList.push({
                  id: item,
                });
              });

              this.infoForm.price = this.priceForm.price;
              this.infoForm.budget = this.priceForm.budget;
              this.getAdAddApiMet(this.infoForm);
            }
          });
        }
      });
    },
    // 重置按钮操作
    resetForm(infoForm, priceForm) {
      this.$refs[infoForm].resetFields();
      this.$refs[priceForm].resetFields();
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  background: rgba(245, 245, 245, 1);
  .el-card {
    margin-top: 20px;
    border: none;
  }
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
    width: 700px;
    .el-input-number--medium {
      width: 250px;
    }

    .upload-demo {
      position: relative;
      .el-upload__tip {
        position: absolute;
        top: 50%;
        left: 380px;
        transform: translateY(-50%);
      }
    }
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both;
  }

  .col-button {
    margin-top: 20px;
    text-align: center;
    .el-button {
      padding: 10px 60px;
    }
  }
}
</style>